import React, { useState } from 'react';
import {
  Box,
  Typography,
  Card,
  CardMedia,
  CardActions,
  IconButton,
  Button,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import {
  Delete,
  PlayArrow,
  Videocam,
} from '@mui/icons-material';
import { MediaUploader } from './MediaUploader';

interface VideoManagerProps {
  contentId: number;
  currentVideos: string[];
  onUpdate: (file: File) => Promise<void>;
  loading?: boolean;
}

export const VideoManager: React.FC<VideoManagerProps> = ({
  contentId,
  currentVideos,
  onUpdate,
  loading = false,
}) => {
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [selectedVideoIndex, setSelectedVideoIndex] = useState<number | null>(null);

  const handleDeleteVideo = (index: number) => {
    setSelectedVideoIndex(index);
    setDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    // 注意：这里需要实现删除视频的API调用
    // 目前API只支持更新视频，不支持删除
    // 实际项目中需要添加删除视频的API
    console.log('删除视频功能需要后端支持');
    setDeleteConfirmOpen(false);
    setSelectedVideoIndex(null);
  };

  const handleVideoUpdate = async (file: File) => {
    await onUpdate(file);
  };

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        视频管理
      </Typography>

      {/* 当前视频 */}
      {currentVideos.length > 0 && (
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" gutterBottom>
            当前视频 ({currentVideos.length}个)
          </Typography>
          
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
            {currentVideos.map((videoUrl, index) => (
              <Box key={index} sx={{ width: { xs: '100%', sm: 'calc(50% - 8px)', md: 'calc(33.33% - 11px)' } }}>
                <Card sx={{ position: 'relative' }}>
                  <Box
                    sx={{
                      position: 'relative',
                      height: 200,
                      bgcolor: 'grey.100',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <video
                      src={videoUrl}
                      style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                      }}
                      controls
                      preload="metadata"
                    />
                  </Box>
                  <CardActions sx={{ position: 'absolute', top: 8, right: 8 }}>
                    <IconButton
                      size="small"
                      onClick={() => handleDeleteVideo(index)}
                      sx={{ 
                        color: 'white',
                        bgcolor: 'rgba(0, 0, 0, 0.5)',
                        '&:hover': {
                          bgcolor: 'rgba(255, 0, 0, 0.7)',
                        }
                      }}
                    >
                      <Delete fontSize="small" />
                    </IconButton>
                  </CardActions>
                </Card>
              </Box>
            ))}
          </Box>
        </Box>
      )}

      {/* 上传新视频 */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" gutterBottom>
          {currentVideos.length > 0 ? '替换视频' : '上传视频'}
        </Typography>
        
        {currentVideos.length > 0 && (
          <Alert severity="info" sx={{ mb: 2 }}>
            上传新视频将替换当前视频
          </Alert>
        )}

        <MediaUploader
          accept="video/*"
          onUpload={handleVideoUpdate}
          loading={loading}
          buttonText="上传视频"
          helperText="支持 MP4、AVI、MOV 格式，视频大小不超过100MB"
          maxSize={100}
        />
      </Box>

      {currentVideos.length === 0 && (
        <Alert severity="info" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Videocam />
          暂无视频，请上传视频文件
        </Alert>
      )}

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除这个视频吗？此操作不可撤销。
          </Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            注意：删除视频功能需要后端API支持，当前仅为演示
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)}>
            取消
          </Button>
          <Button onClick={confirmDelete} color="error" autoFocus>
            确认删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}; 